#include "dlgapartmentedit.h"
#include "ui_dlgapartmentedit.h"
#include "dlgstringedit.h"


DlgApartmentEdit::DlgApartmentEdit(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::DlgApartmentEdit)
{
    ui->setupUi(this);
    ui->list_spaces->setEditTriggers(QAbstractItemView::DoubleClicked);
    connect(ui->btn_ok, SIGNAL(clicked()), this, SLOT(accept()));
    connect(ui->btn_cancel, SIGNAL(clicked()), this, SLOT(reject()));
    connect(ui->list_spaces, SIGNAL(itemActivated(QListWidgetItem*)), this, SLOT(space_item_activated(QListWidgetItem*)));
    connect(ui->list_pdates, SIGNAL(itemActivated(QListWidgetItem*)), this, SLOT(pdate_item_activated(QListWidgetItem*)));
    connect(ui->btn_add_space, SIGNAL(clicked()), this, SLOT(add_space()));
    connect(ui->btn_rem_space, SIGNAL(clicked()), this, SLOT(del_space()));
    ui->ledit_totalspace->setValidator(&m_qd_validator);
    connect(ui->list_spaces, SIGNAL(currentRowChanged(int)), this, SLOT(slist_current_row_changed(int)));
    connect(ui->list_pdates, SIGNAL(currentRowChanged(int)), this, SLOT(plist_current_row_changed(int)));
}

DlgApartmentEdit::~DlgApartmentEdit()
{
    delete ui;
}


void DlgApartmentEdit::setup_connection()
{
    connect(ui->ledit_apartment_num, SIGNAL(textEdited(QString)), this, SLOT(data_changed()));
    connect(ui->ledit_totalspace, SIGNAL(textEdited(QString)), this, SLOT(data_changed()));
    connect(ui->tedit_comments, SIGNAL(textChanged()), this, SLOT(data_changed()));
    connect(ui->combo_rcount, SIGNAL(currentIndexChanged(QString)), this, SLOT(data_changed()));
    connect(ui->list_spaces, SIGNAL(itemChanged(QListWidgetItem*)), this, SLOT(data_changed()));
    connect(ui->list_spaces, SIGNAL(), this, SLOT(data_changed()));
    connect(ui->btn_rem_space, SIGNAL(clicked()), this, SLOT(data_changed()));
    connect(ui->combo_rcount, SIGNAL(currentIndexChanged(QString)), this, SLOT(process_rcount()));
}

void DlgApartmentEdit::data_to_form()
{
    if(mqh_data.isEmpty()) return;

    ui->lable_h_addr->setText(mp_dbms->get_house_addr(mqh_data.value(FLD_APDB_HSINDEX)));
    ui->lable_h_type->setText(mp_dbms->get_house_types(true).at(mp_dbms->get_house_type(mqh_data.value(FLD_APDB_HSINDEX))));
    m_h_type = mp_dbms->get_house_type(mqh_data.value(FLD_APDB_HSINDEX));
    if(mqh_data.size() < 2)   return;
    ui->list_spaces->clear();
    ui->list_pdates->clear();
    ui->ledit_apartment_num->setText(mqh_data.value(FLD_APDB_NUMBER).toString());
    ui->combo_rcount->setCurrentIndex(mqh_data.value(FLD_APDB_RCOUNT).toInt()-1);
    ui->ledit_totalspace->setText(mqh_data.value(FLD_APDB_TSPC).toString());
    mqvh_spaces = mqh_data.value(FLD_APDB_LSPSHASH).toHash();
    mqvh_pdates = mqh_data.value(FLD_APDB_PDATEHASH).toHash();
    mqstrl_ids = mqvh_spaces.keys();
    update_spaces_list();
}

void DlgApartmentEdit::form_to_data()
{
    mqh_data[FLD_APDB_RCOUNT] = ui->combo_rcount->currentIndex()+1;
    mqh_data[FLD_APDB_COMMENTS] = ui->tedit_comments->toPlainText();
    mqh_data[FLD_APDB_LSPSHASH] = mqvh_spaces;
    mqh_data[FLD_APDB_PDATEHASH] = mqvh_pdates;
    mqh_data[FLD_APDB_TSPC] = ui->ledit_totalspace->text().toDouble();
    mqh_data[FLD_APDB_NUMBER] = ui->ledit_apartment_num->text();
}

void DlgApartmentEdit::accept()
{
    if(ui->ledit_apartment_num->text().isEmpty())
    {
        lakhMsgE()<<RUSTR("Ошибка! Не указан номер жилого помещения.");
        return;
    }
    double space = 0;
    foreach(QVariant qv_space, mqvh_spaces)
        space+= qv_space.toDouble();
    if(space < 0.1)
    {
        lakhMsgE()<<RUSTR("Ошибка. Общая жилая площадь нереально маленькая.");
        return;
    }
    if(space > ui->ledit_totalspace->text().toDouble())
    {
        lakhMsgE()<<RUSTR("Ошибка. Общая жилая площадь превышает полную площадь помещения.");
        return;
    }
    return QDialog::accept();
}


void DlgApartmentEdit::set_focus_fld(int fld)
{
    switch(fld)
    {
    case FLD_APDB_RCOUNT:  ui->combo_rcount->setFocus();
                    return;
    case FLD_APDB_TSPC:  ui->ledit_totalspace->setFocus();
                    return;
    case FLD_APDB_COMMENTS:  ui->tedit_comments->setFocus();
                    return;
    };
    ui->ledit_apartment_num->setFocus();
}

void DlgApartmentEdit::space_item_activated(QListWidgetItem */*p_item*/)
{
    int r = ui->list_spaces->currentRow();
    DlgStringEdit *p_se = new DlgStringEdit();
    p_se->set_data(QString::number(mqvh_spaces.value(mqstrl_ids.at(r)).toDouble()), RUSTR("Метраж жилой площади (кв.м.)"));
    p_se->set_double_validator();
    if(p_se->exec())
    {
        if(p_se->is_changed())
        {
            mqvh_spaces[mqstrl_ids.at(r)] = p_se->get_data().toDouble();
            update_spaces_list();
            ui->list_spaces->setCurrentRow(r);
            data_changed();
        }
    }
    delete p_se;
}

void DlgApartmentEdit::pdate_item_activated(QListWidgetItem *p_item)
{
    DlgStringEdit *p_se = new DlgStringEdit();
    p_se->set_data(p_item->text(), RUSTR("Дата приватизации"));
    p_se->set_date_editor();
    if(p_se->exec())
    {
        if(p_se->is_changed())
        {
            int r = ui->list_spaces->currentRow();
            mqvh_pdates[mqstrl_ids.at(r)] = QVariant(p_se->get_date_data());
            update_spaces_list();
            data_changed();
        }
    }
    delete p_se;
}



void DlgApartmentEdit::add_space()
{
    if(ui->list_spaces->count() >= (ui->combo_rcount->currentIndex() + 1))
    {
         lakhMsgE()<<RUSTR("Ошибка. Кол-во жилых площадей не может превышать кол-во комнат.");
         return;
    }
    int r = ui->list_spaces->currentRow();
    int house_type = mp_dbms->get_house_type(mqh_data.value(FLD_APDB_HSINDEX));
    if(house_type == 0)
    {
        if(mqvh_spaces.size() >= 1)
        {
            lakhMsg()<<RUSTR("Внимание. В квартире(комнате) данного типа указыается одна жилая площадь.");
           return;
        }
    }
    QString qstr_id  = HousingDBMS::gen_hash_str_key();
    mqvh_spaces[qstr_id] = QVariant(double(0.0));
    mqvh_pdates[qstr_id] = QVariant(QDate());
    update_spaces_list();
    ui->list_spaces->setCurrentRow(r);
}

void DlgApartmentEdit::del_space()
{
    int r = ui->list_spaces->currentRow();
    if(r == -1)
    {
        lakhMsgE()<<RUSTR("Ошибка. Не выбрана жилая площадь");
        return;
    }

    if(ui->list_spaces->count() == 1)
    {
        lakhMsgE()<<RUSTR("Ошибка. Должна быть минимум одна жилая площадь");
        return;
    }

    QString qstr_id = mqstrl_ids.at(r);
    mqvh_spaces.remove(qstr_id);
    mqvh_pdates.remove(qstr_id);
    update_spaces_list();
}

void DlgApartmentEdit::process_rcount()
{
    if(m_h_type == 1) ui->combo_rcount->setCurrentIndex(0);
    int rcount = ui->combo_rcount->currentIndex() +1;
    if(rcount < mqvh_spaces.size())
    {
        while(rcount < mqvh_spaces.size())
        {
            mqvh_spaces.remove(mqstrl_ids.last());
            mqvh_pdates.remove(mqstrl_ids.last());
        }
    }

    if(m_h_type < 2)
    {
        update_spaces_list();
        return;
    }
    if(rcount > mqvh_spaces.size())
    {
        int spcs_count = mqvh_spaces.size();
        for(int i = 0; i < (rcount - spcs_count); i++)
        {
            QString qstr_id = HousingDBMS::gen_hash_str_key();
            mqvh_spaces[qstr_id] = QVariant(double(0.0));
            mqvh_pdates[qstr_id] = QVariant(QDate());
        }
    }
    update_spaces_list();
}


void DlgApartmentEdit::slist_current_row_changed(int row)
{
    ui->list_pdates->setCurrentRow(row);
}

void DlgApartmentEdit::plist_current_row_changed(int row)
{
    ui->list_spaces->setCurrentRow(row);
}


void DlgApartmentEdit::update_spaces_list()
{
    ui->list_pdates->clear();
    ui->list_spaces->clear();
    mqstrl_ids = mqvh_spaces.keys();

    for(int i = 0; i<mqstrl_ids.size(); i++)
    {
        ui->list_spaces->addItem(RUSTR("№%1: ").arg(i+1) + mqvh_spaces.value(mqstrl_ids.at(i)).toString());
        QDate qd_prv = mqvh_pdates.value(mqstrl_ids.at(i)).toDate();
        if(!qd_prv.isValid())
            ui->list_pdates->addItem(RUSTR("в собственности города"));
        else
            ui->list_pdates->addItem(qd_prv.toString("dd.MM.yyyy"));
    }

}
